package ffmpegWrapper;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import utils.StaticUtils;

public class FfmpegLocator {

	private final String RESOURCE = "/ffmpegWrapper/executable/";
	
	private final String[] DLLS = new String[]{"avcodec-55.dll", "avdevice-55.dll",
												"avfilter-3.dll", "avformat-55.dll",
												"avutil-52.dll", "postproc-52.dll",
												"swresample-0.dll", "swscale-2.dll"
												};
	
	public final String FFMPEG  = "ffmpeg.exe",
						FFPROBE = "ffprobe.exe",
						FFPLAY  = "ffplay.exe";
	
	private File _path;
	
	public FfmpegLocator(){ //To avoid copying each time, check for files existence. Moreover, initiate once in the main.
		
		File temp = new File(System.getProperty("java.io.tmpdir"), "mgtFfWrapper-1");
		if (!temp.exists()) {
			temp.mkdirs();
			temp.deleteOnExit();
		} //add an else if exist
		
		if (!new File(temp, DLLS[0]).exists()){
			
			for (String dll : DLLS){
				File file = new File(temp, dll);
				if (!file.exists()) 
					copyFile(StaticUtils.implode(new String[]{RESOURCE, dll}, ""), file);
			}
			
			for (String exe : new String[]{FFMPEG, FFPROBE, FFPLAY}){
				File file = new File(temp, exe);
				if (!file.exists()) 
					copyFile(StaticUtils.implode(new String[]{RESOURCE, exe}, ""), file);
			}
		}
		_path = temp.getAbsoluteFile();
	}
	
	
	private void copyFile(String path, File dest) throws RuntimeException {
		InputStream input = null;
		OutputStream output = null;
		try {
			input = getClass().getResourceAsStream(path);
			output = new FileOutputStream(dest);
			byte[] buffer = new byte[1024];
			int l;
			while ((l = input.read(buffer)) != -1) {
				output.write(buffer, 0, l);
			}
		} catch (IOException e) {
			throw new RuntimeException("Cannot write file "
					+ dest.getAbsolutePath());
		} finally {
			if (output != null) {
				try {
					output.close();
				} catch (Throwable t) {
					;
				}
			}
			if (input != null) {
				try {
					input.close();
				} catch (Throwable t) {
					;
				}
			}
		}
	}
	
	public File getFfPath(String exe){
		return new File(_path, exe);
	}
	
}
